﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.DAL;
using WXYW.BLL;
using System.Configuration;

namespace WXYW
{
    /// <summary>
    /// 朱经理 21:59:56
    /// 当点击通知后点击 打印 出来发货调拨单 选择保存后 再显示发货 当点击发货后单子自动就走到下一个流程了
    /// 朱经理 22:01:50
    /// 这4个按钮你就给排序下 返回 发货 打印 通知
    /// </summary>
    public partial class SendProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindApplicationForm();
            }
        }

        private void BindApplicationForm()
        {
            try
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.GetApplicationFormDetailByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                RMACodeLabel.Text = form.ApplicationCode;
                runningNumberLabel.Text = form.RunningNumber;
                companyLabel.Text = form.User.FullName;
                receiveTimeLabel.Text = form.ReceiveDateTime != null ? Convert.ToDateTime(form.ReceiveDateTime).ToString("yyyy-MM-dd") : "";
                addressLabel.Text = form.User.UserAddress;
                sendEmailTextBox.Text = form.SendDateTime != null ? Convert.ToDateTime(form.SendDateTime).ToString("yyyy-MM-dd") : "";
                contactLabel.Text = form.User.ContactPerson;
                faxLabel.Text = form.User.UserFax;
                phoneNumberLabel.Text = form.User.UserPhone;
                emailLabel.Text = form.User.UserEmail;
                sendEmailTextBox.Text = DateTime.Now.ToString("yyyy-MM-dd");
                mobilePhoneLbl.Text = form.User.UserMobilePhone;
                smsTxtBox.Text = string.Format("神州数码网络客服中心提示 尊敬的{0}客户您好，您送修的RMA NO.{1}已修复并已安排发货，您可致电01058859855查询相关物流信息，神州数码客服中心01082707718",
                    form.User.ContactPerson, form.ApplicationCode);

                ApplicationProductService Productservice = new ApplicationProductService();
                ApplicationQuatationFormModel model = Productservice.GetQuatationFormModelProducts(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                List<ApplicationProduct> products = Productservice.GetProductShouldSend(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]), ContextService.CurrentAccount.UserID);
                productGridView.DataSource = products;
                productGridView.DataBind();

                //if (form.ApplicationProduct.Where(p => p.Status.Equals("维修完毕待发货") && !p.NoticeClientDateTime.HasValue).Count() > 0)
                if (products.Where(p => !p.SendBackTime.HasValue && !p.NoticeClientDateTime.HasValue).Count() > 0)
                {
                    notifyLinkButton.Enabled = true;
                }
                else
                {
                    notifyLinkButton.Enabled = false;
                }

                //if (form.ApplicationProduct.Where(p => p.Status.Equals("维修完毕待发货") && p.NoticeClientDateTime.HasValue && p.RequisitionForm == null).Count() > 0)
                if (products.Where(p => !p.SendBackTime.HasValue && p.NoticeClientDateTime.HasValue).Count() > 0)
                {
                    printLnkBtn.Enabled = true;
                }
                else
                {
                    printLnkBtn.Enabled = false;
                }

                //if (form.ApplicationProduct.Where(p => p.Status.Equals("维修完毕待发货") && (p.IsDiaoBo.HasValue && p.IsDiaoBo == true) && !p.SendBackTime.HasValue).Count() > 0)
                if (products.Where(p => !p.SendBackTime.HasValue && p.NoticeClientDateTime.HasValue).Count() > 0)
                {
                    sendLinkButton.Enabled = true;
                }
                else
                {
                    sendLinkButton.Enabled = false;
                }

                printLnkBtn.OnClientClick = string.Format("window.open('DBForm.aspx?{0}={1}', '神州数码客服中心发货调拨单','width=600px, height=400px, top=200px, left=200px'); return false;", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "SendProductForm.aspx -> BindApplicationForm");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息获取发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        protected void productGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
            }
        }

        private void InitialEmailPanel()
        {
            ApplicationService applicatonservice = new ApplicationService();
            ApplicationForm applicaton = applicatonservice.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            if (!applicaton.UserReference.IsLoaded)
            {
                applicaton.UserReference.Load();
            }
            if (!applicaton.ApplicationProduct.IsLoaded)
            {
                applicaton.ApplicationProduct.Load();
            }
            string products = string.Empty;

            ApplicationProductService Productservice = new ApplicationProductService();
            List<ApplicationProduct> productList = Productservice.GetProductShouldSend(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]), ContextService.CurrentAccount.UserID);
            foreach (ApplicationProduct product in productList)
            {
                if (!product.ProductTypeReference.IsLoaded)
                {
                    product.ProductTypeReference.Load();
                }

                if (string.IsNullOrEmpty(products))
                {
                    products = product.ProductType.ProductTypeName;
                }
                else
                {
                    products += "," + product.ProductType.ProductTypeName;
                }
            }

            if(!ContextService.CurrentAccount.ServiceStationReference.IsLoaded)
            {
                ContextService.CurrentAccount.ServiceStationReference.Load();
            }

            emailLabel.Text = applicaton.User.UserEmail;
            Label1.Text = applicaton.User.ContactPerson;
            toLabel.Text = applicaton.User.UserEmail;
            bodyTextBox.Text = string.Format(ConfigurationManager.AppSettings["SendProductEmailB"].ToString(), applicaton.User.ContactPerson, applicaton.ApplicationCode, products, DateTime.Now, applicaton.User.UserAddress, ContextService.CurrentAccount.ServiceStation.Phone + " " + ContextService.CurrentAccount.ServiceStation.ContactPerson);
        }

        /// <summary>
        /// 点击“通知”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void notifyLinkButton_Click(object sender, EventArgs e)
        {
            notificationModalPopupExtender.Show();
            InitialEmailPanel();
        }

        /// <summary>
        /// 发送邮件通知
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void sendEmailLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                EmailService.SendEmail(emailLabel.Text, "发货通知", bodyTextBox.Text);

                ApplicationService applicatonservice = new ApplicationService();
                ApplicationForm applicationForm = applicatonservice.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                applicationForm.NortificationDatetime = DateTime.Now;
                applicatonservice.UpdateApplication(applicationForm);

                if (!applicationForm.ApplicationProduct.IsLoaded)
                {
                    applicationForm.ApplicationProduct.Load();
                }

                ApplicationProductService productService = new ApplicationProductService();

                List<ApplicationProduct> products = productService.GetProductShouldSend(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]), ContextService.CurrentAccount.UserID);

                foreach (ApplicationProduct product in products)
                {
                    if (!product.NoticeClientDateTime.HasValue)
                    {
                        product.NoticeClientDateTime = DateTime.Now;
                        productService.UpdateProduct(product);
                    }
                }

                if (!string.IsNullOrEmpty(mobilePhoneLbl.Text))
                {
                    SMSService.SendSMS(smsTxtBox.Text, mobilePhoneLbl.Text);
                }

                Response.Write(string.Format("<script language='JavaScript'> alert( '邮件通知已经发送给客户！');location.href= '{0}?{1}={2}' </script> ", "SendProductForm.aspx", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));

                BindApplicationForm();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "SendProductForm.aspx -> sendEmailLinkButton_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }
        

        /// <summary>
        /// 点击发货按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void sendLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                ApplicationProductService productService = new ApplicationProductService();
                
                List<ApplicationProduct> products = productService.GetProductShouldSend(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]), ContextService.CurrentAccount.UserID);
                
                foreach (ApplicationProduct product in products)
                {
                    if (product.RepairCompleteDateTime.HasValue && !product.SendBackTime.HasValue)
                    {
                        product.Status = "已发货待客户收货确认";
                        product.SendWay = "B";
                        product.SendBackTime = DateTime.Now;
                    }
                    productService.UpdateProduct(product);
                }

                if (form.ApplicationProduct.Where(p => !p.SendBackTime.HasValue).Count() == 0)
                {
                    form.Status = "已发货待客户收货确认";
                    form.SendBackDateTime = DateTime.Now;
                    service.UpdateApplication(form);
                }
                service.UpdateApplication(form);
                Response.Write(string.Format("<script language='JavaScript'> alert( '已发货，请等待客户收货确认！');location.href= 'FinishMaintaince.aspx' </script> "));
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "SendProductForm.aspx->sendLinkButton_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }
    }
}
